package com.wanglei.runner;

import com.wanglei.domain.entity.Article;
import com.wanglei.mapper.ArticleMapper;
import com.wanglei.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *1. 在应用启动时把博客的浏览量存储到redis中
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);
        //list 转 map (stream流方式)
        //坑 redis中存long 1 存的是 1L 1L这样是无法自增的 所以这里用Integer代替Long
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(),
                        article ->  article.getViewCount().intValue()
                ));
        //存储到redis map类型用setCacheMap!!!
        redisCache.setCacheMap("article:viewCount",viewCountMap);
    }
}
